package com.example.demo.controller;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

@RestController
public class ImageController {

    @Autowired
    private COSClient cosClient;

    @Value("${tencent.cos.bucket-name}")
    private String bucketName;

    @PostMapping("/api/upload-image")
    public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return Map.of("code", 400, "message", "文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Map.of("code", 400, "message", "请输入图片文件");
        }

        // 检查文件大小
        if (file.getSize() > 5 * 1024 * 1024) {
            return Map.of("code", 400, "message", "文件大小不能超过5MB");
        }

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
        String fileName = UUID.randomUUID() + fileExtension;

        // 保存文件到腾讯云 COS
        try {
            // 将 MultipartFile 转换为临时文件
            Path tempFilePath = Paths.get(System.getProperty("java.io.tmpdir"), fileName);
            file.transferTo(tempFilePath.toFile());

            // 上传到腾讯云 COS，指定文件夹为 post-image
            String cosKey = "post-image/" + fileName; // 指定 COS 中的路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, cosKey, tempFilePath.toFile());

            // 设置文件类型
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(contentType); // 根据文件类型设置
            putObjectRequest.setMetadata(metadata);

            cosClient.putObject(putObjectRequest);

            // 删除临时文件
            Files.delete(tempFilePath);

            // 生成文件访问 URL
            String imageUrl = "https://" + bucketName + ".cos." + cosClient.getClientConfig().getRegion().getRegionName() + ".myqcloud.com/" + cosKey;

            // 返回图片 URL
            return Map.of("code", 200, "message", "图片上传成功",  "url", imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return Map.of("code", 500, "message", "图片上传失败: " + e.getMessage());
        }
    }
}
